<template>
  <div class="dashboard-container">
    <div class="dashboard-editor-container">
      <!-- <github-corner class="github-corner" /> -->

      <!-- 添加年份选择器 -->
      <div class="year-selector">
        <el-select v-model="selectedYear" placeholder="请选择年份" @change="fetchData">
          <el-option
            v-for="year in yearOptions"
            :key="year"
            :label="year + '年'"
            :value="year"
          />
        </el-select>
      </div>

      <el-row style="background:#fff;padding:16px 16px 0;margin-bottom:32px;">
        <el-col :xs="24" :sm="24" :lg="12">
          <div class="chart-wrapper">
            <div class="chart-title">严西湖花山片区取样断面平均温度</div>
            <TempChart :chart-data="temperatureData" />
          </div>
        </el-col>
        <el-col :xs="24" :sm="24" :lg="12">
          <div class="chart-wrapper">
            <div class="chart-title">严西湖花山片区取样断面PH值</div>
            <PhChart :chart-data="phData" />
          </div>
        </el-col>
      </el-row>

      <el-row :gutter="32">
        <el-col :xs="24" :sm="24" :lg="8">
          <div class="chart-wrapper">
            <div class="chart-title">取样断面溶解氧含量</div>
            <DisOxChart :chart-data="dissolvedOxygenData" />
          </div>
        </el-col>
        <el-col :xs="24" :sm="24" :lg="8">
          <div class="chart-wrapper">
            <div class="chart-title">取样断面化学需氧量</div>
            <ChOxChart :chart-data="chemicalOxygenData" />
          </div>
        </el-col>
        <el-col :xs="24" :sm="24" :lg="8">
          <div class="chart-wrapper">
            <div class="chart-title">取样断面氨氮含量</div>
            <AmNiChart :chart-data="ammoniaNitrogenData" />
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { getYearlyData } from '@/api/waterQualityMonitor'
import GithubCorner from '@/components/GithubCorner'
import ChOxChart from './dashboard/ChOxChart.vue'
import DisOxChart from './dashboard/DisOxChart.vue'
import AmNiChart from './dashboard/AmNiChart.vue'
import PhChart from './dashboard/phChart.vue'
import TempChart from './dashboard/tempChart.vue'

export default {
  name: 'Dashboard',
  components: {
    GithubCorner,
    PhChart,
    TempChart,
    ChOxChart,
    DisOxChart,
    AmNiChart
  },
  data() {
    return {
      selectedYear: new Date().getFullYear(), // 默认选择当前年份
      yearOptions: [], // 年份选项
      temperatureData: { expectedData: [] },
      phData: { expectedData: [] },
      dissolvedOxygenData: { expectedData: [] },
      chemicalOxygenData: { expectedData: [] },
      ammoniaNitrogenData: { expectedData: [] },
      loading: false,
      monthLabels: []
    }
  },
  created() {
    this.initYearOptions()
    this.fetchData()
  },
  methods: {
    initYearOptions() {
      const currentYear = new Date().getFullYear()
      // 生成最近5年的年份选项，可以根据需求调整年份范围
      this.yearOptions = Array.from({ length: 5 }, (_, index) => currentYear - index)
    },
    formatDate(timestamp) {
      const date = new Date(timestamp)
      return `${date.getMonth() + 1}月`  // 只显示月份，因为年份已经在选择器中显示
    },
    async fetchData() {
      if (!this.selectedYear) return

      this.loading = true
      try {
        const response = await getYearlyData(this.selectedYear)
        console.log('后端返回的完整响应:', response)

        // 确保数据是数组
        const data = Array.isArray(response.data) ? response.data : []
        console.log('解构后的 data:', data)

        // 如果数据为空，直接退出
        if (!data.length) {
          console.warn('数据为空，未进行任何处理。')
          return
        }

        // 确保数据按时间排序
        const sortedData = data.sort((a, b) => {
          if (!a.recordTime || !b.recordTime) {
            console.warn('某些数据项缺少 recordTime:', a, b)
            return 0
          }
          return new Date(a.recordTime) - new Date(b.recordTime)
        })

        console.log('排序后的数据:', sortedData)

        // 生成月份标签
        this.monthLabels = sortedData.map(item => this.formatDate(item.recordTime))

        // 更新图表数据
        this.temperatureData = {
          expectedData: sortedData.map(item => item.temperature),
          monthLabels: this.monthLabels
        }

        this.phData = {
          expectedData: sortedData.map(item => item.ph),
          monthLabels: this.monthLabels
        }

        this.dissolvedOxygenData = {
          expectedData: sortedData.map(item => item.dissolvedOxygen),
          monthLabels: this.monthLabels
        }

        this.chemicalOxygenData = {
          expectedData: sortedData.map(item => item.chemicalOxygenDemand),
          monthLabels: this.monthLabels
        }

        this.ammoniaNitrogenData = {
          expectedData: sortedData.map(item => item.ammoniaNitrogenContent),
          monthLabels: this.monthLabels
        }
      } catch (error) {
        console.error('获取数据失败:', error)
        this.$notify.error({
          title: '错误',
          message: '获取数据失败'
        })
      } finally {
        this.loading = false
      }
    }

  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.dashboard-editor-container {
  padding: 32px;
  background-color: rgb(240, 242, 245);
  position: relative;

  .github-corner {
    position: absolute;
    top: 0;
    border: 0;
    right: 0;
  }

  .year-selector {
    margin-bottom: 20px;
    text-align: right;
    
    .el-select {
      width: 120px;
    }
  }

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px 0;
    margin-bottom: 32px;
    position: relative;
    text-align: center;
  }

  .chart-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 16px;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    top: 0px;
  }
}

@media (max-width:1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}
</style>